<style type="text/css">
#title_cart{
	color: #03378A;
    font-weight: bold;
    padding-left: 10px;
}
</style>

<?php
require_once 'config.php';
 
/*********************************************************
*                 CHECKOUT FUNCTIONS 
*********************************************************/
function saveOrder(){
			$ship_firstname = $_SESSION['ship_firstname'];
                        $ship_lastname = $_SESSION['ship_lastname'];
			$ship_title =$_SESSION['ship_title'];
			$ship_phone =$_SESSION['ship_phone'];
			$ship_email =$_SESSION['ship_email'];
			$ship_province =$_SESSION['ship_province'];
			$ship_city =$_SESSION['ship_city'];
			$ship_address =$_SESSION['ship_address'];
			$ship_country =$_SESSION['ship_country'];			
			$sql_sipping="INSERT INTO tbl_shipping(ship_lastname, ship_firstname, ship_title, ship_address, ship_telephone, ship_email, ship_province, ship_city, ship_contry) VALUES('$ship_firstname', '$ship_lastname','$ship_title', '$ship_address', '$ship_phone', '$ship_email', '$ship_province', '$ship_city', '$ship_country')";						
	mysql_query($sql_sipping);
        //header('Location: '.W_ROOT.'/success.php');
        
        
	
	//send email to seller
		/*
	  start function send mail 
	*/
	
 if(isset($_POST['btnConfirm'])){

	 
	 // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to  = 'sales@khm.co' . ', '; // note the comma
    $email_to .= $_POST['hidShippingEmail'];
     
     
    function died($error) {
        // your error code can go here
        echo $error;
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
     
    
	
    if(//validation expected data exists for Billing 
		!isset($_POST['hidPaymentFirstName']) ||
		!isset($_POST['hidPaymentLastName']) ||
        !isset($_POST['hidPaymentAddress']) ||
        !isset($_POST['hidPaymentPhone']) ||
        !isset($_POST['hidPaymentEmail'])||
	// validation expected data exists for shipping
		!isset($_POST['hidShippingFirstName']) ||
        !isset($_POST['hidShippingLastName']) ||
        !isset($_POST['hidShippingAddress']) ||
        !isset($_POST['hidShippingPhone']) ||
        !isset($_POST['hidShippingEmail']))	
		{
        died('We are sorry, but there appears to be a problem with the form you submitted.');      
    }
	//for bill to....
	$first_name_bill=$_POST['hidPaymentFirstName'];
	$last_name_bill=$_POST['hidPaymentLastName'];
	$fullname_bill = $_POST['hidPaymentFirstName']." ".$_POST['hidPaymentLastName']; // required
	$telephone_bill = $_POST['hidPaymentPhone']; // not required
    $address_bill = $_POST['hidPaymentAddress'];		
    $email_from_bill = $_POST['hidPaymentEmail']; // required
    //for ship to ......
	$first_name=$_POST['hidShippingFirstName']; 
	$last_name=$_POST['hidShippingLastName'];
    $fullname = $_POST['hidShippingFirstName']." ".$_POST['hidShippingLastName']; // required
	$telephone = $_POST['hidShippingPhone']; // not required
    $address = $_POST['hidShippingAddress'];
    $email_from = $_POST['hidShippingEmail']; // required
  
   // var_dump($_SESSION['profile_shipping_email']);
    
    //var_dump($email_from);
    //die();
 
    
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
//   if($_SESSION['profile_shipping_email']!=$email_from) {
//    $error_message .= 'Note*: Please check your email in Shipping information again.<br />';
//  }
  
   if(!preg_match($email_exp,$email_from_bill)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$first_name_bill)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }

  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$last_name_bill)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }
  if(strlen($address) < 2) {
    $error_message .= 'The Address you entered do not appear to be valid.<br />';
  }
  if(strlen($address_bill) < 2) {
    $error_message .= 'The Address you entered do not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.<br /><br />";
	function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
	}
	// function send for Bill to...
	$email_message = "Bill to:<br />";
	$email_message .= "First Name: &nbsp;".clean_string($fullname_bill)."<br />";
    $email_message .= "Address: &nbsp;".clean_string($address_bill)."<br />";
	$email_message .= "Telephone: &nbsp;".clean_string($telephone_bill)."<br />"; 
    $email_message .= "Email: &nbsp;".clean_string($email_from_bill)."<br /><br />";   
	
	//function send for ship to...
	$email_message .= "Ship to:<br />";
	$email_message .= "First Name: &nbsp;".clean_string($fullname)."<br />";
    $email_message .= "Address: &nbsp;".clean_string($address)."<br />";
	$email_message .= "Telephone: &nbsp;".clean_string($telephone)."<br />";
    $email_message .= "Email: &nbsp;".clean_string($email_from)."<br /><br />";
    
	
$cartContent = getCartContent();
$numItem = count($cartContent);
if($numItem>0){
	
 $email_message .='<table  border="0" id="table_shop_cart" width="100%">
	<tr id="title_cart">
        <td width="10%" style="padding-left:10px">Image</td>
    	<td width="40%">Product Name</td>
        <td width="20%" align="left">Price</td>
        <td width="15%" align="left">Quantity</td>
        <td width="25%" align="left">Subtotal</td>
    </tr>';

$subtoral = 0;
$total = 0;
for ($i=0; $i<$numItem; $i++){
	extract($cartContent[$i]);
	  $subtotal = $price * $ct_qty;
	   $total += $price * $ct_qty;
       $email_message .='<tr class="row_cart">';
       $email_message .='<td class="product_name_cart"><img src="'.W_ROOT.'/company/product/uploads/'.$thumbnail.'"/></td>';  
       $email_message .='<td class="product_name_cart">'.$product_name.'</td>';   
       $email_message .='<td class="product_price_cart">'.$price."$".'</td>';
	   $email_message .='<td class="product_price_cart">'.$ct_qty.'</td>'; 
       $email_message .='<td class="product_price_cart">'.$subtotal."$".'</td>';
       $email_message .='</tr>';
   
       }
     
	    $email_message .='<tr bgcolor="#a5a3a4"><td colspan="4"></td></tr>';
	    $email_message .='<tr>';
    	$email_message .='<td colspan="2"></td>';
        $email_message .='<td id="total_text_cart">Total :</td>';
        $email_message .='<td class="product_price_cart">'. $total."$".' </td>';   
        $email_message .='</tr>';
        $email_message .='<tr bgcolor="#a5a3a4"><td colspan="5"></td></tr>';
        $email_message .='</table>';
    }  
 }

 
 // create email headers
    $email_subject = 'Thanks to '.$first_name.' for buy from KHM';
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	$headers .= 'From: KHM <sales@khm.co>' . "\r\n";
    $headers .= 'mailed-by: <sales@khm.co>' . "\r\n";


mail($email_to, $email_subject, $email_message, $headers); 
?>
 
<!-- include your own success html here --> 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php


/*

  the function send mail for end function

*/
	
	//the end send email
 
	
	
	
	$orderId       = 0;
	$shippingCost  = 5;
	$requiredField = array('hidShippingFirstName', 'hidShippingLastName', 'hidShippingTitle', 'hidShippingAddress', 'hidShippingPhone',
						   'hidShippingMobile', 'hidShippingEmail', 'hidShippingState', 'hidShippingCity', 'hidShippingCountry', 'hidShippingPostalCode',
						   'hidPaymentFirstName', 'hidPaymentLastName', 'hidPaymentTitle', 'hidPaymentAddress', 'hidPaymentPhone', 
						   'hidPaymentMobile', 'hidPaymentEmail', 'hidPaymentState', 'hidPaymentCity', 'hidPaymentCountry', 'hidPaymentPostalCode');
						   
	if (checkRequiredPost($requiredField)) {
	    extract($_POST);
		
		// make sure the first character in the 
		// customer and city name are properly upper cased
		$hidShippingFirstName = ucwords($hidShippingFirstName);
		$hidShippingLastName  = ucwords($hidShippingLastName);
		$hidShippingCity      = ucwords($hidShippingCity);
		$hidPaymentFirstName  = ucwords($hidPaymentFirstName);
		$hidPaymentLastName   = ucwords($hidPaymentLastName);
		$hidPaymentCity       = ucwords($hidPaymentCity);
				
		$cartContent = getCartContent();
		$numItem     = count($cartContent);
                //var_dump($_SESSION['acc_id']);
               // die();
		
		// save order & get order id
		$sql = "INSERT INTO tbl_order(od_date, od_last_update, od_shipping_first_name, od_shipping_last_name, od_shipping_title, od_shipping_address, od_shipping_telephone, 
		                              od_shipping_mobile, od_shipping_email, od_shipping_state, od_shipping_city, od_shipping_country, od_shipping_postal_code, 
                                      od_payment_first_name, od_payment_last_name, od_payment_title, od_payment_address, od_payment_telephone, 
									  od_payment_mobile, od_payment_email, od_payment_state, od_payment_city, od_payment_country, od_payment_postal_code, user_id, user_session_id)
                VALUES (NOW(), NOW(), '$hidShippingFirstName', '$hidShippingLastName', '$hidShippingTitle', '$hidShippingAddress', '$hidShippingPhone', 
						   '$hidShippingMobile', '$hidShippingEmail', '$hidShippingState', '$hidShippingCity', '$hidShippingCountry', '$hidShippingPostalCode', 
						   '$hidPaymentFirstName', '$hidPaymentLastName', '$hidPaymentTitle', '$hidPaymentAddress', '$hidPaymentPhone', 
						   '$hidPaymentMobile', '$hidPaymentEmail', '$hidPaymentState', '$hidPaymentCity', '$hidPaymentCountry', '$hidPaymentPostalCode', '".$_SESSION['acc_id']."', '".$_SESSION['orderSesion']."')";
	
		$result = mysql_query($sql);
                $_SESSION['OrderLastId'] = mysql_insert_id();
		
		// get the order id
		$orderId = dbInsertId();
		
		if ($orderId) {
			// save order items
			for ($i = 0; $i < $numItem; $i++) {
				$sql = "INSERT INTO tbl_order_item(od_id, pd_id, od_qty, oi_status, user_histoStatusDel, delete_orderRow_status)
						VALUES ($orderId, {$cartContent[$i]['pd_id']}, {$cartContent[$i]['ct_qty']}, 0, 1, 1)";
				$result = mysql_query($sql);					
			}
		
			
			// update product top_sale
			for ($i = 0; $i < $numItem; $i++) {
				$product_id = $cartContent[$i]['product_id'];
				$sql = "UPDATE tblproduct SET top_sale = top_sale+1 WHERE id = $product_id";
				//echo $sql;exit;
				$result = mysql_query($sql);
				
			}
			
			
			 //then remove the ordered items from cart
			for ($i = 0; $i < $numItem; $i++) {
				$sql = "DELETE FROM tbl_cart
				        WHERE ct_id = {$cartContent[$i]['ct_id']}";
				$result = mysql_query($sql);					
			}							
		}					
	}
	
	return $orderId;
}

/*
	Get order total amount ( total purchase + shipping cost )
*/
/*function getOrderAmount($orderId)
{
	$orderAmount = 0;
	
	$sql = "SELECT SUM(pd_price * od_qty)
	        FROM tbl_order_item oi, tblproduct p 
		    WHERE oi.pd_id = p.pd_id and oi.od_id = $orderId
			
			UNION
			
			SELECT od_shipping_cost 
			FROM tbl_order
			WHERE od_id = $orderId";
	$result = mysql_query($sql);

	if (dbNumRows($result) == 2) {
		$row = dbFetchRow($result);
		$totalPurchase = $row[0];
		
		$row = dbFetchRow($result);
		$shippingCost = $row[0];
		
		$orderAmount = $totalPurchase + $shippingCost;
	}	
	
	return $orderAmount;	
}*/

?>